<template>
  <div class="loan-slider-container">
    <div class="slider-labels">
      <div class="min-label">{{ formatValue(min) }}元</div>
      <div class="max-label">{{ formatValue(max) }}元</div>
    </div>
    
    <div class="slider-controls">
      <button 
        class="control-btn decrease-btn" 
        @click="decreaseValue" 
        :disabled="modelValue <= min"
      >
        <el-icon><Minus /></el-icon>
      </button>
      
      <div class="slider-track" ref="sliderTrack" @click="handleTrackClick">
        <div class="slider-fill" :style="{ width: fillWidth + '%' }"></div>
        <div 
          class="slider-handle" 
          :style="{ left: fillWidth + '%' }"
          @mousedown="startDrag"
          @touchstart="startDrag"
        >
          <div class="handle-inner"></div>
        </div>
      </div>
      
      <button 
        class="control-btn increase-btn" 
        @click="increaseValue" 
        :disabled="modelValue >= max"
      >
        <el-icon><Plus /></el-icon>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Minus, Plus } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: {
    type: Number,
    required: true
  },
  min: {
    type: Number,
    default: 0
  },
  max: {
    type: Number,
    default: 100
  },
  step: {
    type: Number,
    default: 1
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

// 滑块轨道引用
const sliderTrack = ref(null);

// 计算填充宽度百分比
const fillWidth = computed(() => {
  return ((props.modelValue - props.min) / (props.max - props.min)) * 100;
});

// 格式化数值（添加千分位分隔符）
const formatValue = (value) => {
  return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 减少值
const decreaseValue = () => {
  if (props.modelValue - props.step >= props.min) {
    updateValue(props.modelValue - props.step);
  } else {
    updateValue(props.min);
  }
};

// 增加值
const increaseValue = () => {
  if (props.modelValue + props.step <= props.max) {
    updateValue(props.modelValue + props.step);
  } else {
    updateValue(props.max);
  }
};

// 更新值
const updateValue = (newValue) => {
  // 确保值在范围内
  newValue = Math.max(props.min, Math.min(props.max, newValue));
  
  // 按步长调整值
  const steps = Math.round((newValue - props.min) / props.step);
  newValue = props.min + steps * props.step;
  
  // 发出更新事件
  emit('update:modelValue', newValue);
  emit('change', newValue);
};

// 处理轨道点击
const handleTrackClick = (event) => {
  if (!sliderTrack.value) return;
  
  const trackRect = sliderTrack.value.getBoundingClientRect();
  const clickPosition = event.clientX - trackRect.left;
  const trackWidth = trackRect.width;
  
  const percentage = clickPosition / trackWidth;
  const newValue = props.min + percentage * (props.max - props.min);
  
  updateValue(newValue);
};

// 拖动相关变量
let isDragging = false;
let startX = 0;
let startValue = 0;

// 开始拖动
const startDrag = (event) => {
  event.preventDefault();
  isDragging = true;
  
  // 记录起始位置和值
  startX = event.type === 'mousedown' ? event.clientX : event.touches[0].clientX;
  startValue = props.modelValue;
  
  // 添加移动和结束事件监听
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('touchmove', handleDrag);
  document.addEventListener('mouseup', endDrag);
  document.addEventListener('touchend', endDrag);
};

// 处理拖动
const handleDrag = (event) => {
  if (!isDragging || !sliderTrack.value) return;
  
  const currentX = event.type === 'mousemove' ? event.clientX : event.touches[0].clientX;
  const trackRect = sliderTrack.value.getBoundingClientRect();
  const trackWidth = trackRect.width;
  
  const deltaX = currentX - startX;
  const deltaPercentage = deltaX / trackWidth;
  const deltaValue = deltaPercentage * (props.max - props.min);
  
  updateValue(startValue + deltaValue);
};

// 结束拖动
const endDrag = () => {
  isDragging = false;
  
  // 移除事件监听
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('touchmove', handleDrag);
  document.removeEventListener('mouseup', endDrag);
  document.removeEventListener('touchend', endDrag);
};

// 组件卸载时清理事件监听
onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('touchmove', handleDrag);
  document.removeEventListener('mouseup', endDrag);
  document.removeEventListener('touchend', endDrag);
});
</script>

<style scoped lang="scss">
.loan-slider-container {
  width: 100%;
  padding: 10px 0;
}

.slider-labels {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  
  .min-label, .max-label {
    font-size: 12px;
    color: #909399;
  }
}

.slider-controls {
  display: flex;
  align-items: center;
  
  .control-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border: 1px solid #dcdfe6;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      background-color: #f5f7fa;
    }
    
    &:active {
      background-color: #e4e7ed;
    }
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
  
  .slider-track {
    flex: 1;
    height: 6px;
    background-color: #e4e7ed;
    border-radius: 3px;
    margin: 0 15px;
    position: relative;
    cursor: pointer;
    
    .slider-fill {
      position: absolute;
      height: 100%;
      background-color: #3a4a6d;
      border-radius: 3px;
      left: 0;
      top: 0;
    }
    
    .slider-handle {
      position: absolute;
      width: 20px;
      height: 20px;
      background-color: #fff;
      border: 2px solid #3a4a6d;
      border-radius: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      cursor: grab;
      
      &:active {
        cursor: grabbing;
      }
      
      .handle-inner {
        width: 8px;
        height: 8px;
        background-color: #3a4a6d;
        border-radius: 50%;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}
</style>